package com.yoke.controller;

import com.yoke.common.JsonMessage;
import com.yoke.common.UserUtil;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.common.interceptor.LoginInterceptor;
import com.yoke.common.interceptor.NotLogin;
import com.yoke.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by jiangzeyin on 2017/5/9.
 */
@Controller
public class LoginControl extends NginxBaseControl {

    @RequestMapping(value = "login.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String login() {
        Object user = session.getAttribute(LoginInterceptor.SESSION_NAME);
        if (user != null)
            session.invalidate();
        return "login";
    }

    /**
     * 登录方法
     *
     * @param name
     * @param pwd
     * @return
     */
    @RequestMapping(value = "login_to", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String login_ok(String name, String pwd) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("用户登录：").append(name).append(",IP：").append(ip);
        stringBuffer.append(",浏览器：").append(getUserAgent());
        try {
            boolean flag = UserUtil.login(name, pwd);
            if (flag) {
                stringBuffer.append("，结果：").append("OK");
                session.setAttribute(LoginInterceptor.SESSION_NAME, name);
                return JsonMessage.getString(200, "登录成功");
            } else {
                stringBuffer.append("，结果：").append("faild");
            }
            return JsonMessage.getString(400, "登录失败，请输入正确的密码和账号");
        } catch (RuntimeException e) {
            stringBuffer.append("，结果：").append("error");
            return JsonMessage.getString(500, e.getLocalizedMessage());
        } finally {
            SystemLog.LOG().info(stringBuffer.toString());
        }
    }
}
